package services;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSONObject;

import models.User;
import play.cache.Cache;
import play.mvc.Http.Request;
import utils.BizConstants;
import utils.wechat.HttpUtil;
import utils.wechat.MessageUtil;
import utils.wechat.TokenUtil;
import vos.weChat.Article;
import vos.weChat.NewsMessage;
import vos.weChat.TextMessage;
import vos.weChat.TokenVo;

/** 
 * 核心服务类    
 */  
public class WeChatService { 
	private static final SimpleDateFormat dateTimeFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static final SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
    /** 
     * 处理微信发来的请求 
     * @param endwork 
     * @param beginwork 
     *  
     * @param request 
     * @return 
     */  
    public static String processRequest(String beginwork, String endwork, Request request) {  
        String resMessage="";
	    try{
	    	Map<String, String> requestMap = MessageUtil.parseXml(request);  
	         // 发送方帐号（open_id）  
	 	    String fromUserName = requestMap.get("FromUserName");  
	 	    // 公众帐号  
	 	    String toUserName = requestMap.get("ToUserName");  
		    if(StringUtils.isNotEmpty(beginwork)||StringUtils.isNotEmpty(endwork)){
				 Date date =new Date();
				 String dateStr=dateFormater.format(date);
				 Date begin=dateTimeFormater.parse(dateStr+" "+beginwork);
				 Date end=dateTimeFormater.parse(dateStr+" "+endwork);
				 if(date.getTime()<begin.getTime()||date.getTime()>end.getTime()){
//					 	TextMessage textMessage = new TextMessage();  
//		                textMessage.setToUserName(fromUserName);  
//		                textMessage.setFromUserName(toUserName);  
//		                textMessage.setCreateTime(new Date().getTime());  
//		                textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);  
//		                textMessage.setFuncFlag(0);
//		                String content=SystemParamService.getByCacheId(BizConstants.WECHAT_AUTOMATIC_REPLAY);
//		                textMessage.setContent(content);
//		                // 将文本消息对象转换成xml字符串  
//		                resMessage = MessageUtil.textMessageToXml(textMessage); 
					 	customerService(fromUserName);
				 }
				 else{
					 /**
					  * 转发到多客服系统
					  */
		            TextMessage textMessage = new TextMessage();  
	                textMessage.setToUserName(fromUserName);
	                textMessage.setFromUserName(toUserName);
	                textMessage.setCreateTime(new Date().getTime());
	                textMessage.setMsgType(MessageUtil.TRANSFER_CUSTOMER_SERVICE);
	                resMessage = MessageUtil.textMessageToXml(textMessage);
				 }
		    }
	    }catch(Exception e){
	    	e.printStackTrace();
	    }
        return resMessage;
    }
    /**
     * 获取数据库中的token
     */
    public static TokenVo getTokenByCache(){
    	 TokenVo vo=new TokenVo();
    	 String token=(String)Cache.get("weChat_token");
    	 if(StringUtils.isEmpty(token)){
    		 token=SystemParamService.getByCacheId(BizConstants.WECHAT_TOKEN);
    	 }
    	 if(StringUtils.isNotEmpty(token)){
    		 vo=JSONObject.parseObject(token, TokenVo.class);
    	 }
    	 return vo;
    }
    /**
     * 模拟客服发信息
     *
     * @Title: customerService 
     * @param fromUserName
     * @return: void
     */
	public static void customerService(String fromUserName) {
		// TODO Auto-generated method stub
		try{
			String ss="{\"touser\":\""+fromUserName+"\",\"msgtype\":\"text\",\"text\":{\"content\":\"现在客服已下班，给您带来不便请谅解\"}}";
			String token=TokenUtil.getAccessToken();
			String url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+token;
			HttpUtil.doPost(url, ss);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}  
